#include "myhead.h"
#define CLI_PORT 8888
#define CLI_IP "192.168.85.131"
int main()
{
    int sfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sfd == -1)
    {
        perror("socket error");
        return -1;
    }
    printf("socket success cfd=%d", sfd);
    struct sockaddr_in sin;
    sin.sin_addr.s_addr = inet_addr(CLI_IP);
    sin.sin_port = htons(CLI_PORT);
    sin.sin_family = AF_INET;

    if (connect(sfd, (struct sockaddr *)&sin, sizeof(sin)) == -1)
    {
        perror("connext error");
        return -1;
    }
    printf("连接服务器成功");
    pollfd pfds[2];
    pfds[0].fd = 0;          // 检测0号
    pfds[0].events = POLLIN; // 检测读

    pfds[1].fd = sfd;        // 检测sfd
    pfds[1].events = POLLIN; // 检测读
    char wbuf[128] = "";
    while (1)
    {
        int res = poll(pfds, 2, -1);
        // 参数1：文件描述符集合起始地址
        // 参数2：文件描述符个数
        // 参数3：表示永久等待
        if (res == -1)
        {
            perror("poll error");
            return -1;
        }
        printf("poll success");
        if (pfds[0].revents == POLLIN)
        {
            // 清空容器
            bzero(wbuf, sizeof(wbuf));
            // 从终端获取数据
            fgets(wbuf, sizeof(wbuf), stdin);
            wbuf[strlen(wbuf) - 1] = 0;
            if (send(sfd, wbuf, sizeof(wbuf), 0) == -1)
            {
                perror("send error");
                return -1;
            }
        }
        if (pfds[1].revents == POLLIN)
        {
            if (recv(sfd, wbuf, sizeof(wbuf), 0) == 0)
            {
                perror("对端已下线");
                break;
            }
            printf("收到服务器的消息为:%s\n", wbuf);
        }
    }
    close(sfd);
    return 0;
}